<?php

namespace addons\facrm\controller\facrm\contract;

use addons\facrm\library\BackendApi;
use addons\facrm\library\Helper;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 回款管理
 */
class Receivables extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,number,remark';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['payurl'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\contract\Receivables');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 回款列表
     * @ApiParams(name="customer_id", type="int", required=false, description="客户id")
     * @ApiBody ("其它参数参考电脑版")
     */
    public function index()
    {
        $filter_w = array();
        $customer_id = $this->request->param("customer_id");
        if ($customer_id) {
            $filter_w['customer_id'] = $customer_id;
        }
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
                'contract' => function ($customer) {
                    $customer->field('id,name,number');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();

        $result = array("rows" => $list);

        $this->success('', $result);
    }

    /**
     * 回款添加
     * @ApiMethod (POST|GET)
     * @ApiParams(name="customer_id", type="int", required=true, description="客户id")
     * @ApiParams(name="number", type="string", required=true, description="回款编号")
     * @ApiParams(name="contract_id", type="int", required=true, description="合同id")
     * @ApiParams(name="account_id", type="int", required=true, description="收款账户")
     * @ApiParams(name="money", type="int", required=true, description="回款金额")
     * @ApiParams(name="return_time", type="string", required=true, description="回款日期")
     * @ApiParams(name="flow_admin_id", type="int", required=true, description="审批人ID，多个逗号隔开")
     * @ApiParams(name="remark", type="string", required=true, description="备注")
     * @ApiBody ("get获取审批流程config为1是固定审批0是授权。flow_admin_id是固定审批时候的用户ID")
     */
    public function add()
    {
        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();
        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'), url("facrm/flow/index"));
        if ($this->request->isPost()){
            $params = $this->request->post();
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));
            //获取合同情况
            $contractModel = new \app\admin\model\facrm\Contract();
            if (!isset($params['contract_id']))
                $this->error(__('请选择合同'));

            $contract_r = $contractModel->get($params['contract_id']);
            if (!$contract_r)
                $this->error(__('没有找到合同'));

            $params['return_time'] =isset($params['return_time'])&&$params['return_time'] ? strtotime($params['return_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $this->auth->id,
                'check_status' => 0,
                'order_admin_id' => $contract_r->order_admin_id,
            ]);

            if ($params['pay_type']==2){
                //判断是否支持线上收款
                $payConfig=\addons\facrm\library\Order::getPayConfig();
                if (!$payConfig||$payConfig['values']['online_pay']!=1){
                    $this->error(__('线上收款未启用'));
                }
                //如果采用线上收款
                $params['pay_token']=md5(uniqid('pay_token').Random::alnum());//生成支付链接凭证
                $params['flow_admin_id']='';
            }
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                //采用模型验证
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $this->model->validateFailException(true)->validate( $name . '.add');
                $result = $this->model->allowField(true)->save($params);
                $receivables_id = $this->model->id;
                hook("facrm_receivables_add", array_merge($params, ['id' => $receivables_id]));
                Db::commit();
            } catch (ValidateException$e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                if ($params['pay_type']==2){
                    //如果采用线上收款就不需要审核

                }else{
                    $flow->addFlow($receivables_id, $this->auth->id, 'receivables', $flow_r);
                }

                $this->success('',['receivables_id'=>$receivables_id]);
            } else {
                $this->error(__('No rows were inserted'));
            }
        }else{
            if ($flow_r->config==1)//如果固定审批
                $flow_r['flow_admin_id']=$flow->getAdminIds($flow_r,$this->auth->id);

            $this->success('',$flow_r);
        }


    }


    /**
     * 我的下属/回款[添加]
     * @param null $param 和add参数一样
     */
    public function receivablesadd(){

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();
        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'), url("facrm/flow/index"));
        if ($this->request->isPost()){
            $params = $this->request->post();
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));
            //获取合同情况
            $contractModel = new \app\admin\model\facrm\Contract();
            if (!isset($params['contract_id']))
                $this->error(__('请选择合同'));

            $contract_r = $contractModel->get($params['contract_id']);
            if (!$contract_r)
                $this->error(__('没有找到合同'));

            //检查是否有权限
            $Auth = new  \addons\facrm\library\Auth();
            if (!$Auth->checkCustomerAuth($row_c, $this->auth)&&!$this->auth->check('facrm/contract/receivables/add')) {
                $this->error(__("您没有权限"));//
            }
            $this->add();
        }else{
            if ($flow_r->config==1)//如果固定审批
                $flow_r['flow_admin_id']=$flow->getAdminIds($flow_r,$this->auth->id);

            $this->success('',$flow_r);
        }
    }


    /**
     * 修改回款
     * @ApiMethod (POST|GET)
     * @ApiParams(name="id", type="int", required=true, description="回款id")
     * @ApiParams(name="customer_id", type="int", required=false, description="客户id")
     * @ApiParams(name="number", type="string", required=false, description="回款编号")
     * @ApiParams(name="contract_id", type="int", required=false, description="合同id")
     * @ApiParams(name="account_id", type="int", required=false, description="收款账户")
     * @ApiParams(name="money", type="int", required=false, description="回款金额")
     * @ApiParams(name="return_time", type="string", required=false, description="回款日期")
     * @ApiParams(name="flow_admin_id", type="int", required=false, description="审批人ID，多个逗号隔开")
     * @ApiParams(name="remark", type="string", required=false, description="备注")
     * @ApiBody ("更多参数参考电脑版")
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($id);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();

        if ($this->request->isPost()) {
            if ($row->check_status == 2) {
                $this->error(__('通过审核的收款不能再更改'));
            }
            $params = $this->request->post();
            if ($params) {

                isset($params['return_time']) ? $params['return_time']= strtotime($params['return_time']) : '';
                $params['check_status'] = 0;//重新改成待审核状态
                if ($params['pay_type']==2){
                    //判断是否支持线上收款
                    $payConfig=\addons\facrm\library\Order::getPayConfig();
                    if (!$payConfig||$payConfig['values']['online_pay']!=1){
                        $this->error(__('线上收款未启用'));
                    }
                    //如果采用线上收款
                    $params['pay_token']=md5(uniqid('pay_token').Random::alnum());//生成支付链接凭证
                    $params['flow_admin_id']='';
                }

                $result = false;
                Db::startTrans();
                try {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $row->validateFailException(true)->validate($name . '.edit');
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $receivables_id = $row->id;
                    if ($params['pay_type']==2){
                        //如果采用线上收款就不需要审核
                    }else{
                        $flow->addFlow($receivables_id, $this->auth->id, 'receivables', $flow_r);
                    }

                    hook("facrm_receivables_edit", array_merge($params, ['id' => $receivables_id]));
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->success('', ['row'=>$row,'flow'=>$flow_r]);

    }

    /**
     * 删除回款
     * @param string $ids
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();
            //获取合同情况
            $contractModel = new \app\admin\model\facrm\Contract();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    //扣除回款的金额 return_money
                    $contract_r = $contractModel->withTrashed()->find($v['contract_id']);
                    if ($contract_r && $v['check_status'] == 2) {
                        $contract_r->return_money = $contract_r->return_money - $v['money'];
                        $contract_r->save();
                    }

                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 生成在线收款单
     * @param null $ids
     * @return string
     * @throws Exception
     */
    public function payurl($ids = null)
    {
        $ids = $this->request->get("ids");
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->pay_type!=2){
            $this->error(__('不是线上收款单'.$row->pay_type));
        }
        $check_data=\addons\facrm\library\Order::checkPay($row, 'pay',$pay_config);
        if ($check_data['code']!=1){
            $this->error(__($check_data['msg']));
        }
        //如果已经支付了就是续费链接
        if ($row->pay_status == 1) {
            $this->error(__('已经支付'));
        } else {
            //10天就重新刷新支付凭证
            if (!$row->pay_token||(time()-$row->update_time)>864000){
                $row->pay_token = md5($row->id . uniqid() . Random::uuid());
                $row->save();
            }
            $url = addon_url('facrm/order/pay', ['pay_token' => $row->pay_token], '', true);
        }

        $this->success('',['url'=>$url,'qrcode_url'=>addon_url('facrm/order/qrcode',[],false,true)."?text={$url}",'row'=>$row]);
    }
}
